<?php
namespace app\api\controller;

use think\facade\Config;
use app\api\controller\Base;
use app\goods\model\ImsEweiShopGoods;
use app\member\model\ImsEweiShopMemberAddress;
use app\member\model\ImsMcMembers;
use app\member\model\ImsEweiShopMember;
use app\member\model\ImsEweiShopMemberCart;
use app\order\model\ImsEweiShopOrder;
use app\order\model\ImsEweiShopOrderGoods;
use app\wechat\service\PaymentService;
use app\wechat\service\WechatService;
use EasyWeChat\Foundation\Application;
use app\activityNew\model\ImsEweiShopActivity;

class Order extends Base
{
    public function index()
    {

    }

    //请求微信支付
    public function set(){

        $token = $this->request->post('token');
        $pay_type = $this->request->post('pay_type');
        $cart_ids = $this->request->post('cart_ids');
        $address_id = $this->request->post('address_id');
        $integral_price_discount = $this->request->post('integral_price_discount');
        $need_integral = $this->request->post('need_integral');
        $member_card_id = $this->request->post('member_card_id');
        $remark = $this->request->post('remark');

        if (empty($address_id) || $address_id == 'undefined') {
            $this->echojson(1,'请选择配送地址', $token);
        }

        $member = $this->getMemberInfoByToken($token);
        if (empty($member)) {
            $this->echojson(1,'登陆过期，请重新登陆', $token);
        }

        $orderData = [
            'cart_ids'=>explode(',', $cart_ids),
            'address_id'=>$address_id,
            'integral_price_discount'=>$integral_price_discount,
            'pay_type'=>$pay_type,
            'need_integral'=>$need_integral,
            'member_card_id'=>$member_card_id,
            'remark'=>$remark,
        ];
        $orderGoodsData = [];

        $orderRes = ImsEweiShopOrder::mk()->creatOrder($orderData,$member);

        if ($orderRes['code'] != 200) {
            $this->echojson($orderRes['code'],$orderRes['message'], $orderRes);
        }

        $parentid = $orderRes['parentid'];
        $orderid = $orderRes['orderid'];

        //有父订单时候支付父订单总金额，否则只支付当前订单金额
        if ($parentid>0) {
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$parentid])->find();
        }else{
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$orderid])->find();
        }

        // 生成支付参数
        $oCode = $orderInfo['ordersn'];
        $pAmount = $orderInfo['price'];
        $payResult = PaymentService::create($orderInfo['openid'], $oCode, "订单号：{$oCode}", $pAmount, PaymentService::WECHAT_XCX);
        
        $data['orderRes'] = $orderRes;
        $data['pay_state'] = $orderInfo['status'];
        $data['pay_params'] = $payResult['params'];

        $this->echojson(0,'订单提交成功', $data);
    }

 //生成货到付款订单
    public function setSendOrder(){
        $token = $this->request->post('token');
        $pay_type = $this->request->post('pay_type');
        $cart_ids = $this->request->post('cart_ids');
        $address_id = $this->request->post('address_id');
        $integral_price_discount = $this->request->post('integral_price_discount');
        $need_integral = $this->request->post('need_integral');
        $member_card_id = $this->request->post('member_card_id');
        $remark = $this->request->post('remark');

        if (empty($address_id) || $address_id == 'undefined') {
            $this->echojson(1,'请选择配送地址', $token);
        }

        $member = $this->getMemberInfoByToken($token);
        if (empty($member)) {
            $this->echojson(1,'登陆过期，请重新登陆', $token);
        }

        $orderData = [
            'cart_ids'=>explode(',', $cart_ids),
            'address_id'=>$address_id,
            'integral_price_discount'=>$integral_price_discount,
            'pay_type'=>$pay_type,
            'need_integral'=>$need_integral,
            'member_card_id'=>$member_card_id,
            'remark'=>$remark
        ];
        $orderGoodsData = [];

        $orderRes = ImsEweiShopOrder::mk()->creatOrder($orderData,$member);

        if ($orderRes['code'] != 200) {
            $this->echojson($orderRes['code'],$orderRes['message'], $orderRes);
        }

        $parentid = $orderRes['parentid'];
        $orderid = $orderRes['orderid'];

        //有父订单时候支付父订单总金额，否则只支付当前订单金额
        if ($parentid>0) {
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$parentid])->find();
			ImsEweiShopOrder::mk()->where("id=$parentid or parentid=$parentid")->update(['status'=>30]);
        }else{
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$orderid])->find();
			ImsEweiShopOrder::mk()->where(['id'=>$orderid])->update(['status'=>30]);
        }
	

        // 生成支付参数
       // $oCode = $orderInfo['ordersn'];
      //  $pAmount = $orderInfo['price'];
         
        $data['orderRes'] = $orderRes;
        $data['pay_state'] = 30;
        //$data['pay_params'] = $payResult['params'];

        $this->echojson(0,'货到付款订单提交成功', $data);
    }






    //购物车提交订单展示页
    public function confirmOrder(){
        $token = $this->request->post('token');
        $cart_ids = $this->request->post('cart_ids');
        $member = $this->getMemberInfoByToken($token);
        if (empty($member)) {
            $this->echojson(1,'登陆过期，请重新登陆', $token);
        }
        $carWhere = [
            'f.openid' => $member['openid'],
            'f.deleted' => 0,
        ];
        $fields = " f.id,f.selected AS `select`,f.goodsid AS goods_id,f.total AS goods_number,g.thumb,g.title,g.total AS number_stock,g.marketprice AS price,g.isdiscount ";

        $cart_list = ImsEweiShopMemberCart::mk()->alias('f')->leftJoin('ims_ewei_shop_goods g ','f.goodsid = g.id')->field($fields)->where($carWhere)->where('f.id','IN',$cart_ids)->select();

        $addWhere = array();
        $addWhere['openid'] = $member['openid'];
        $addWhere['deleted'] = 0;
        $addWhere['isdefault'] = 1;
        $fields = "id,uniacid,openid,realname as name, mobile as phone, province as provinceid,city as cityid, area as countryid,address as street, isdefault as is_default";
        $defAddr = ImsEweiShopMemberAddress::mk()->where($addWhere)->field($fields)->find();

        if (empty($defAddr)) {
            $defAddr['name'] = '';
            $defAddr['phone'] = '';
            $defAddr['provinceid'] = '';
            $defAddr['cityid'] = '';
            $defAddr['countryid'] = '';
            $defAddr['street'] = '';
        }

        $price_goods = 0;
        $price_goods_act = 0;
        foreach ($cart_list as $k => $v) {
            $price_goods += $v['price'] * $v['goods_number'];
			if($v['isdiscount']==1){
				$price_goods_act += $v['price'] * $v['goods_number'];
			}
        }

        $data = [
            "goods"=> ImsEweiShopMemberCart::formatDatas($cart_list),
            'price_goods'=>$price_goods,
			'price_goods_act'=>$price_goods_act,//参加活动商品的金额
            'is_integral'=>0,
            'integral_price_discount'=>0,
            'price_express'=>0,
            'member_card_list'=>$cart_list,
            'member_goods_discount'=>0,
            'member_discount'=>'0',
            'name'=> $defAddr['name'],
            'phone' => $defAddr['phone'],
            'address_info' => $defAddr['provinceid'].$defAddr['cityid'].$defAddr['countryid'].$defAddr['street'],
        ];
        $this->echojson(0,'获取购物车成功', $data);
    }

    public function orderlist(){
        $token = $this->request->get('token');
        $status = $this->request->get('status');

        $member = $this->getMemberInfoByToken($token);
        if (empty($member)) {
            $this->echojson(1,'登陆过期，请重新登陆', $token);
        }

        $orderWhere = array();
        $orderWhere['openid'] = $member['openid'];
        $orderWhere['uniacid'] = 2;
        $orderWhere['isparent'] = 0;
        $orderWhere['deleted'] = 0;
        switch ($status) {
            case 0:
                $orderWhere['status'] = 0;
                break;
            case 1:
                $orderWhere['status'] = [1,30];
                break;
            case 2:
                $orderWhere['status'] = 2;
                break;
            case 3:
                $orderWhere['status'] = 3;
                break;
            case 4:
                $orderWhere['status'] = 4;
                break;
            default:
                $orderWhere['status'] = $status;
                break;
        }
        

        $fields = "*";
        $data = ImsEweiShopOrder::mk()->where($orderWhere)->field($fields)->order('id desc')->select();

        foreach ($data as $k => $v) {
            $number_goods = 0;
            $v['action'] = ImsEweiShopOrder::getActionArr($v['status']);
            $v['order_no'] = $v['ordersn'];
            $v['order_status'] = $v['status'];
            $v['price_total'] = $v['price'];
            $v['order_status'] = ImsEweiShopOrder::orderStatusStr($v['status']);
            $goods_list = ImsEweiShopOrderGoods::mk()->where(['orderid'=>$v['id']])->select();
            foreach ($goods_list as $key => $val) {
                $val['goods_title'] = $val['title'];
                $val['price_selling'] = $val['price'];
                $val['price_total'] = $val['price'];
                $val['number_goods'] = $val['total'];
                $number_goods += $val['total'];
                $goodInfo = ImsEweiShopGoods::mk()->where(['id'=>$val['goodsid']])->find();
                $val['goods_logo'] = isset($goodInfo['thumb']) ? get_image_full_url($goodInfo['thumb']) : '';
                $val['marketprice'] = isset($goodInfo['marketprice']) ? $goodInfo['marketprice'] : 0;
                $goods_list[$key] = $val;
            }
            $v['goods_list'] = $goods_list;
            $v['number_goods'] = $number_goods;
            $data[$k] = $v;
        }

        $this->echojson(0,'获取订单列表成功', ['list'=>$data]);
    }

    public function orderdetail(){
        $token = $this->request->get('token');
        $order_id = $this->request->get('order_id');

        $member = $this->getMemberInfoByToken($token);
        if (empty($member)) {
            $this->echojson(1,'登陆过期，请重新登陆', $token);
        }

        $data = ImsEweiShopOrder::mk()->where(['id'=>$order_id])->find();
        $data['action'] = ImsEweiShopOrder::getActionArr($data['status'],1);
        $data['express_province'] = iunserializer($data['address'])['province'];
        $data['express_city'] = iunserializer($data['address'])['city'];
        $data['express_area'] = iunserializer($data['address'])['area'];
        $data['express_address'] = iunserializer($data['address'])['address'];
        $data['express_name'] = iunserializer($data['address'])['realname'];
        $data['express_phone'] = iunserializer($data['address'])['mobile'];
        $data['address'] = iunserializer($data['address']);

        $goods_list = ImsEweiShopOrderGoods::mk()->where(['orderid'=>$data['id']])->select();
        foreach ($goods_list as $key => $val) {
            $val['goods_title'] = $val['title'];
            $val['price_selling'] = $val['price'];
            $val['price_total'] = $val['price'];
            $val['number_goods'] = $val['total'];
            $goodInfo = ImsEweiShopGoods::mk()->where(['id'=>$val['goodsid']])->find();
            $val['goods_logo'] = isset($goodInfo['thumb']) ? get_image_full_url($goodInfo['thumb']) : '';
            $val['marketprice'] = isset($goodInfo['marketprice']) ? $goodInfo['marketprice'] : 0;
            $goods_list[$key] = $val;
        }
        $data['goods_list'] = $goods_list;
        $data['price_goods'] = $data['price'];
        $data['pay_price'] = $data['price'];
        $data['order_no'] = $data['ordersn'];
        $data['create_at'] = $data['createtime'];
        $data['pay_type'] = $data['paytype'];
        $data['pay_type_str'] = ImsEweiShopOrder::orderPaytypeStr($data['status'],$data['pay_type']);
        $data['express_send_no'] = $data['expresssn'];
        $data['order_status'] = ImsEweiShopOrder::orderStatusStr($data['status']);
        $data['status'] = $data['status']==30 ? 1 : $data['status'];

        $this->echojson(0,'获取订单详情成功', $data);
    }

    public function removeOrder(){
        $token = $this->request->post('token');
        $order_id = $this->request->post('order_id');

        $data = ImsEweiShopOrder::mk()->update(['deleted' => 1], ['id' => $order_id]);
        $this->echojson(0,'删除订单成功', $data);
    }

    public function cancelOrder(){
        $token = $this->request->post('token');
        $order_id = $this->request->post('order_id');

        $data = ImsEweiShopOrder::mk()->update(['status' => -1], ['id' => $order_id]);
        $this->echojson(0,'取消订单详情成功', $data);
    }

    public function wxpay(){

        $token = $this->request->post('token');
        $order_no = $this->request->post('order_no');

        //有父订单时候支付父订单总金额，否则只支付当前订单金额
        $orderInfo = ImsEweiShopOrder::mk()->where(['ordersn'=>$order_no])->find();
        if ($orderInfo['parentid']>0) {
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$orderInfo['parentid']])->find();
        }

        // 生成支付参数
        $oCode = $orderInfo['ordersn'];
        $oName = "订单号： {$oCode}";
        $oAmount = $orderInfo['price'];//'0.01';
        $payResult = PaymentService::create($orderInfo['openid'], $oCode, $oName, $oAmount, PaymentService::WECHAT_XCX);
        
        $data['orderRes'] = $order_no;
        $data['pay_state'] = $orderInfo['status'];
        $data['pay_params'] = $payResult['params'];

        $this->echojson(0,'获取微信支付成功', $data);
    }

    public function extendOrder(){

    }

    public function confirmReceipt(){
        $token = $this->request->post('token');
        $order_id = $this->request->post('order_id');

        $data = ImsEweiShopOrder::mk()->update(['status' => 3], ['id' => $order_id]);
        $this->echojson(0,'确认收货成功', $data);
    }

    /**
     * 小程序B2b支付
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setV2(){

        $token = $this->request->post('token');
        $pay_type = $this->request->post('pay_type');
        $cart_ids = $this->request->post('cart_ids');
        $address_id = $this->request->post('address_id');
        $member_card_id = $this->request->post('member_card_id');
        $remark = $this->request->post('remark');

        if (empty($address_id) || $address_id == 'undefined') {
            $this->echojson(1,'请选择配送地址', $token);
        }

        $member = $this->getMemberInfoByToken($token);
        if (empty($member)) {
            $this->echojson(1,'登陆过期，请重新登陆', $token);
        }

        $orderData = [
            'cart_ids'=>explode(',', $cart_ids),
            'address_id'=>$address_id,
            'pay_type'=>$pay_type,
            'member_card_id'=>$member_card_id,
            'remark'=>$remark,
        ];
        $orderGoodsData = [];

        $orderRes = ImsEweiShopOrder::mk()->creatOrder($orderData,$member);

        if ($orderRes['code'] != 200) {
            $this->echojson($orderRes['code'],$orderRes['message'], $orderRes);
        }

        $parentid = $orderRes['parentid'];
        $orderid = $orderRes['orderid'];

        //有父订单时候支付父订单总金额，否则只支付当前订单金额
        if ($parentid>0) {
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$parentid])->find();
        }else{
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$orderid])->find();
        }

        // 生成支付参数
        $b2bPay = new Pay();
        // 获取用户会话密钥（需通过code换取）
        $code = $this->request->post('code'); // 小程序前端获取的临时code
        $appid = Config::get('wechat.wechat_b2b.app_id');
        $app_secret = Config::get('wechat.wechat_b2b.app_secret');
        $session_info = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code");

        $session_data = json_decode($session_info, true);
        $orderInfo['price'] = 0.01;
        // 构造订单数据
        $order = [
            'trade_no' => $orderInfo['ordersn'],
            'amount' => $orderInfo['price'],      // 订单金额（元）
            'openid' => $orderInfo['openid'],
        ];

        // 发起支付请求
        $payResult = $b2bPay->createPayment($order, $session_data['session_key']);

        $data['orderRes'] = $orderRes;
        $data['pay_state'] = $orderInfo['status'];
        $data['pay_params'] = $payResult;

        $this->echojson(0,'订单提交成功', $data);
    }

    /**
     * 待支付订单支付
     * @return void
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wxpayV2(){
        $token = $this->request->post('token');
        $order_no = $this->request->post('order_no');

        //有父订单时候支付父订单总金额，否则只支付当前订单金额
        $orderInfo = ImsEweiShopOrder::mk()->where(['ordersn'=>$order_no])->find();
        if ($orderInfo['parentid']>0) {
            $orderInfo = ImsEweiShopOrder::mk()->where(['id'=>$orderInfo['parentid']])->find();
        }

        // 生成支付参数
        $b2bPay = new Pay();
        // 获取用户会话密钥（需通过code换取）
        $code = $this->request->post('code'); // 小程序前端获取的临时code
        $appid = Config::get('wechat.wechat_b2b.app_id');
        $app_secret = Config::get('wechat.wechat_b2b.app_secret');
        $session_info = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code");

        $session_data = json_decode($session_info, true);
        $orderInfo['price'] = 0.01;
        // 构造订单数据
        $order = [
            'trade_no' => $orderInfo['ordersn'],
            'amount' => $orderInfo['price'],      // 订单金额（元）
            'openid' => $orderInfo['openid'],
        ];

        // 发起支付请求
        $payResult = $b2bPay->createPayment($order, $session_data['session_key']);

        $data['orderRes'] = $order_no;
        $data['pay_state'] = $orderInfo['status'];
        $data['pay_params'] = $payResult;
        $this->echojson(0,'获取微信支付成功', $data);
    }

}